package com.shujia.kafka;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.Properties;

/**
 * @author shujia
 */
public class Demo4Tran {
    public static void main(String[] args) throws Exception {
        //擦黄健配置文件对象
        Properties properties = new Properties();
        //设置broker列表
        properties.setProperty("bootstrap.servers", "master:9092,node2:9092,node2:9092");

        //对数据进行序列化的类，String
        properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        properties.setProperty("transactional.id", "12312");

        //创建kafka生产者
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);

        //开启事务
        kafkaProducer.initTransactions();
        kafkaProducer.beginTransaction();

        //发送数据
        kafkaProducer.send(new ProducerRecord<>("tran", "java"));

        System.out.println("第一条数据发送成功");
        Thread.sleep(10000);

        kafkaProducer.send(new ProducerRecord<>("tran", "spark"));

        //提交事务
        kafkaProducer.commitTransaction();

        //关闭连接
        kafkaProducer.close();

        /*
         * kafka-console-consumer.sh --bootstrap-server  master:9092,node1:9092,node2:9092 --from-beginning --isolation-level read_committed  --topic tran
         */
    }
}
